package com.iptv.grape.ui.dlg;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.iptv.grape.R;
import com.iptv.grape.load_apk.LoadApk;
import com.iptv.grape.load_apk.LoadListener;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ToastUtil;

import java.io.File;

public class LoadDlg extends Dialog implements View.OnClickListener {
    //在构造方法里提前加载了样式
    private Context context;//上下文
    private ProgressBar pbLoadApk;
    private TextView tvLoadApk;
    private String url,name;
    private int size;
    public LoadDlg(Context context,String url,String name,int size) {
        super(context, R.style.MeDlg);//加载dialog的样式
        this.context = context;
        this.url = url;
        this.name = name;
        this.size = size;

    }
    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int wat = msg.what;
            switch (wat){
                case 10:
                    tvLoadApk.setText("开始下载");
                    break;
                case 11:
                    AppLog.getCurLog().e(msg.obj,"===",size);
                    int pro =((int)msg.obj)*100/(size/1024);
                    if(pro>100)
                        pro =100;
                    else if (pro<0)
                        pro =0;
                    pbLoadApk.setProgress(pro);
                    tvLoadApk.setText("已下载："+pro+"%");
                    break;
                case 13:
                case 14:
                    ToastUtil.show(msg.obj);
                    break;
                case 111:
                    String path = (String)msg.obj;
                    try {
                        AppLog.getCurLog().e("size=",LoadApk.ISTC().getFileSize(name),">>>path ="+path);
                        installIntent(path);
                    } catch (Exception e) {
                        ToastUtil.show(e.getMessage());
                        LoadApk.ISTC().delFile(path);
                    }
                    dismiss();
                    break;
            }
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSet();
        setContentView(R.layout.dlg_loadapk);
        pbLoadApk = findViewById(R.id.pbLoadApk);
        pbLoadApk.setMax(100);
        tvLoadApk = findViewById(R.id.tvLoadApk);
        findViewById(R.id.btnLoadApk).setOnClickListener(this);
        LoadApk.ISTC().download2(url,name,"loadApk",new LoadListener() {
            @Override
            public void start(long max) {
                Message msg= mHandler.obtainMessage();
                msg.what = 10;
                mHandler.sendMessage(msg);
            }

            @Override
            public void loading(int progress) {
                Message msg= mHandler.obtainMessage();
                msg.what = 11;
                msg.obj = progress;
                mHandler.sendMessage(msg);
            }

            @Override
            public void complete(String path) {
                Message msg= mHandler.obtainMessage();
                msg.what = 111;
                msg.obj = path;
                mHandler.sendMessage(msg);

            }

            @Override
            public void fail(int code, String message) {
                Message msg= mHandler.obtainMessage();
                msg.what = 13;
                msg.obj = message;
                msg.arg1 = code;
                mHandler.sendMessage(msg);
            }

            @Override
            public void loadfail(String message) {
                Message msg= mHandler.obtainMessage();
                msg.what = 14;
                msg.obj = message;
                mHandler.sendMessage(msg);
            }
        });

    }

    /**
     * 安装
     * 7.0 以上记得配置 fileProvider
     */
    private void installIntent(String path) throws  Exception{
            File file = new File(path);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                String authority = context.getApplicationContext().getPackageName() + ".fileProvider";
                Uri fileUri = FileProvider.getUriForFile(context.getApplicationContext(), authority, file);
                intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            context.startActivity(intent);

    }


    private void initSet() {
        Window window = this.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.CENTER;
        window.setAttributes(layoutParams);
        setCanceledOnTouchOutside(false);//点击外部Dialog消失
    }


    @Override
    public void onClick(View v) {
        LoadApk.ISTC().cancel(name);
        dismiss();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

}
